<!-- 费用管理 -->
<template>
  <div class="page-container">
    <div class="quick-search">
      <div
        v-for="item in quickSearchData"
        :key="item.key"
        class="quick-search-item"
        :class="[item.checked ? 'quick-search-item-checked' : '']"
        @click="quickSearchClick(item)"
      >
        <div class="quick-search-item-label">{{ item.label }}</div>
        <div class="quick-search-item-value" :class="[item.checked ? 'quick-search-item-value-checked' : '']">{{ item.value + '元' }}</div>
      </div>
    </div>
    <list-searcher :searchList="searchList" v-model:searchForm="queryParam" @loadData="onSearch" @reset="handleReset">
      <template #feeNameIdList>
        <a-select
          :allow-clear="true"
          multiple
          v-model="queryParam.feeNameIdList"
          placeholder="请选择"
          @change="changeFeeName"
          @clear="clearFeeName"
        >
          <template #header>
            <div style="padding: 6px 12px">
              <a-checkbox v-model="allChangeFeeStatus" :indeterminate="feeIndeterminate" @change="allChangeFeeName">全选</a-checkbox>
            </div>
          </template>
          <a-option v-for="item in dict.feeNameIdEnum" :key="item.value" :value="item.value">
            {{ item.label }}
          </a-option>
        </a-select>
      </template>
    </list-searcher>
    <table-index :table="table" @loadData="loadData">
      <template #createTime="{ record }">
        <div v-if="record.level == 1">{{ record.createTime || '-' }}</div>
      </template>
      <template #orderInfo="{ record }">
        <template v-if="record.level == 1">
          <div>
            自营订单号：
            <template v-if="record.orderCode">
              <a-link v-if="usePermission('svms:order:short-order.detail')" class="a-link" @click="onALinkClick(record)">
                {{ record.orderCode }}
              </a-link>
              <span v-else>{{ record.orderCode }}</span>
            </template>
            <template v-else>-</template>
          </div>
          <div class="order-info-item">
            渠道订单号：
            <template v-if="record.channelOrderCode">
              <a-link v-if="usePermission('svms:order:short-order.detail')" class="a-link" @click="onALinkClick(record)">
                {{ record.channelOrderCode }}
              </a-link>
              <span v-else>{{ record.channelOrderCode }}</span>
            </template>
            <template v-else>-</template>
          </div>
          <div class="order-info-item">创建时间：{{ record.orderCreateTime || '-' }}</div>
          <div class="order-info-item">渠道来源：{{ record.channelTypeName || '-' }}</div>
        </template>
      </template>

      <template #carInfo="{ record }">
        <template v-if="record.level == 1">
          <div>车牌号：{{ record.carLicenseNo || '-' }}</div>
          <div>车型：{{ record.carModelName || '-' }}</div>
        </template>
      </template>

      <template #site="{ record }">
        <template v-if="record.level == 1">
          <div>取：{{ record.siteName || '-' }}</div>
          <div>还：{{ record.returnSiteName || '-' }}</div>
        </template>
      </template>

      <template #timeRange="{ record }">
        <template v-if="record.level == 1">
          <div>预计租赁周期：{{ record.startTime + '-' + record.endTime || '-' }}</div>
          <div>实际租赁周期：{{ getText(record) }}</div>
        </template>
      </template>

      <template #memberName="{ record }">
        <template v-if="record.level == 1">
          <div>{{ record.memberName }}</div>
          <div>{{ record.memberPhone }}</div>
        </template>
      </template>

      <template #expand-icon="{ expanded }">
        <icon-plus-circle style="font-size: 20px; color: #0256ff" v-if="!expanded" />
        <icon-minus-circle style="font-size: 20px; color: #0256ff" v-else />
      </template>
      <!-- <template #expand-row="{ record }">
      <span v-if="record.feeDetailList && record.feeDetailList.length">
        <div v-for="(item, index) in record.feeDetailList" :key="index" class="second-stage">
          <div>{{ item.feeCategoryName || '-' }}</div>
          <span v-if="item.childrenList && item.childrenList.length">
            <div v-for="(ele, k) in item.childrenList" :key="k" class="third-stage">
              {{ ele.itemName || '-' }}
            </div>
          </span>
        </div>
      </span>
    </template> -->
    </table-index>
  </div>

  <orderfee ref="orderfeepage" @feepageConfirm="feepageConfirm" />
  <!-- 修改费用 -->
  <EditFee ref="edit_fee" @ok="loadData" />
  <qcode-modal
    v-model:visible="payQCodeModal"
    :details="clickRecord"
    @close="payQCodeClose"
    :qcodeTitle="qcodeTitle"
    :qcodeCfLoading="qcodeCfLoading"
    @confirm="qcodeConfirm"
    :from="qrcodeFrom"
  />
</template>

<script setup name="ShortOrdeListCost" lang="ts">
  import EditFee from '@/views/order/short-order/components/edit-fee-modal.vue'
  import orderfee from '@/views/confirmFee/order/index.vue'
  import qcodeModal from '@/views/confirmFee/modals/qcode-modal.vue'

  import { ref, reactive, onMounted, computed } from 'vue'
  import { useTable } from '@/hooks/table'
  import { usePermission } from '@/hooks/usePermission'
  import { usePageDict } from '@/hooks/useDict'
  import { getList, getNums } from '@/api/finance/costConfirm'
  import dayjs from 'dayjs'
  import { cancelPay } from '@/api/common'
  import { Message } from '@arco-design/web-vue'
  import useNavigate from '@/hooks/useNavigate'

  const { navigateTo } = useNavigate()

  const orderfeepage = ref()
  const qrcodeFrom = ref('')
  const qcodeCfLoading = ref(false)
  const qcodeTitle = ref('收款码')
  const payQCodeModal = ref(false)
  const dict = usePageDict('costConfirmDict')
  const clickRecord = ref({})
  const edit_fee = ref()

  // 查询条件
  const searchList = computed(() => {
    return [
      {
        label: '应结时间',
        prop: 'createTimeRange',
        type: 'i-range-picker',
        attrs: {
          showTime: true,
          timePickerProps: {
            defaultValue: ['00:00:00', '23:23:59'],
          },
        },
        change: (value = []) => {
          queryParam.createTimeBegin = value[0]
          queryParam.createTimeEnd = value[1]
        },
      },
      {
        label: '预计取车时间',
        prop: 'startTimeRange',
        type: 'i-range-picker',
        attrs: {
          showTime: true,
          timePickerProps: {
            defaultValue: ['00:00:00', '23:23:59'],
          },
        },
        change: (value = []) => {
          queryParam.startTimeBegin = value[0]
          queryParam.startTimeEnd = value[1]
        },
      },
      {
        label: '预计还车时间',
        prop: 'endTimeRange',
        type: 'i-range-picker',
        attrs: {
          showTime: true,
          timePickerProps: {
            defaultValue: ['00:00:00', '23:23:59'],
          },
        },
        change: (value = []) => {
          queryParam.endTimeBegin = value[0]
          queryParam.endTimeEnd = value[1]
        },
      },
      {
        label: '实际取车时间',
        prop: 'actualStartRange',
        type: 'i-range-picker',
        attrs: {
          showTime: true,
          timePickerProps: {
            defaultValue: ['00:00:00', '23:23:59'],
          },
        },
        change: (value = []) => {
          queryParam.actualStartTimeBegin = value[0]
          queryParam.actualStartTimeEnd = value[1]
        },
      },
      {
        label: '实际还车时间',
        prop: 'actualEndTimeRange',
        type: 'i-range-picker',
        attrs: {
          showTime: true,
          timePickerProps: {
            defaultValue: ['00:00:00', '23:23:59'],
          },
        },
        change: (value = []) => {
          queryParam.actualEndTimeBegin = value[0]
          queryParam.actualEndTimeEnd = value[1]
        },
      },
      {
        label: '费用状态',
        prop: 'feeStatuses',
        type: 'a-select',
        options: dict.orderFeeStatusEnum,
        attrs: {
          multiple: true,
        },
      },
      { label: '订单号', prop: 'orderCodeChannel', type: 'a-input' },
      { label: '承租人信息', prop: 'memberNamePhone', type: 'a-input' },
      { label: '车牌号', prop: 'carLicenseNoLike', type: 'a-input' },
      {
        label: '费用名称',
        slot: 'feeNameIdList',
      },
      {
        label: '费用类型',
        prop: 'feeType',
        type: 'a-select',
        options: dict.orderFeeTypeEnum,
      },
      {
        label: '收支类型',
        prop: 'costType',
        type: 'a-select',
        options: dict.costTypeEnum,
      },
      {
        label: '订单来源',
        prop: 'orderSource',
        type: 'a-select',
        options: dict.orderSourceEnum,
      },
      {
        label: '订单渠道',
        prop: 'channelTypeList',
        type: 'sysdict-select',
        attrs: { multiple: true, code: 'short_order_channel_type' },
        addable: false,
      },
      { label: '订单状态', prop: 'orderStatusList', type: 'a-select', options: dict.orderStatusEnum, multiple: true },
    ]
  })

  const quickSearchData = ref([
    {
      key: 1,
      label: '本月费用',
      value: 23,
      checked: false,
    },
    {
      key: 2,
      label: '待收款费用',
      value: 23,
      checked: false,
    },
    {
      key: 3,
      label: '待付款费用',
      value: 23,
      checked: false,
    },
    {
      key: 4,
      label: '应收未收押金',
      value: 23,
      checked: false,
    },
    {
      key: 5,
      label: '应退未退押金',
      value: 23,
      checked: false,
    },
  ])

  const queryParam = reactive<any>({
    createTimeRange: [],
    startTimeRange: [],
    endTimeRange: [],
    actualStartRange: [],
    actualEndTimeRange: [],
  })

  // table 配置
  const table = useTable({
    pagination: {
      page: 1,
      pageSize: 10,
      showSizePicker: false,
      pageCount: 1,
    },
    columns: [
      { title: '费用应结时间', dataIndex: 'createTime', width: 280, slotName: 'createTime' },
      { title: '费用名称', dataIndex: 'feeName' },
      { title: '费用类型', dataIndex: 'feeTypeName' },
      {
        title: '收支类型',
        dataIndex: 'costTypeName',
        width: 180,
      },
      {
        title: '费用金额',
        dataIndex: 'totalAmount',
        width: 180,
        unit: '元',
      },
      {
        title: '待结金额',
        dataIndex: 'receiveAmount',
        render: (record: any) => {
          if (record.receiveAmount || record.receiveAmount == 0) {
            return Math.abs(record.receiveAmount)
          } else {
            return '-'
          }
        },
        unit: '元',
      },
      { title: '订单信息', slotName: 'orderInfo', width: 280 },
      { title: '车辆信息', slotName: 'carInfo', width: 200 },
      { title: '承租人', dataIndex: 'memberName', slotName: 'memberName' },
      { title: '取还车门店', slotName: 'site', width: 200 },
      { title: '订单来源', dataIndex: 'orderSourceName' },
      { title: '租赁周期', slotName: 'timeRange', width: 460 },
      { title: '生成节点', dataIndex: 'createNodeName' },
      { title: '收支方式', dataIndex: 'payTypeName' },
      { title: '费用状态', dataIndex: 'feeStatusName' },
      { title: '收付款时间', dataIndex: 'payTime', width: 180 },
      { title: '确认时间', dataIndex: 'confirmTime', width: 180 },
      { title: '确认人', dataIndex: 'confirmUserName' },
      { title: '费用备注', dataIndex: 'remark', width: 160, ellipsis: true },
      { title: '结算备注', dataIndex: 'settlementRemark', width: 160, ellipsis: true },
    ],
    operates: [
      {
        label: '确认费用',
        permission: 'svms:finance:costConfirm.confirm',
        // 费用类型 线下费用且配置渠道订单自动同步关闭时 && 费用状态：未收款、未付款和已驳回时
        show: (record: any) =>
          record.feeType == 1 && (record.feeStatus == 1 || record.feeStatus == 3 || record.feeStatus == 5) && record.refId == null,
        method: (record: any) => {
          orderfeepage.value.show(JSON.stringify([record.id]), record)
        },
      },
      {
        label: '修改费用',
        // permission: 'svms:finance:costConfirm.edit',
        // 费用类型 线下费用且配置渠道订单自动同步关闭时 && 待收/付款、已驳回时，支持修改费用
        // canModify仅加
        show: (record: any) => record.canModify == 1,
        method: (record: any) => {
          edit_fee.value.open(record.id)
        },
      },
      // ------------
      {
        label: '收款码',
        permission: 'svms:finance:costConfirm.qrcode',
        show: (record: any) => record.level == 1 && record.feeStatus == 6,
        method: (record: any) => {
          console.log('收款码', record)

          qrcodeFrom.value = 'costShortOrderQRCode'
          qcodeTitle.value = '收款码'
          clickRecord.value = {
            ...record,
            bizType: 1,
            refId: record.orderId,
          }
          payQCodeModal.value = true
        },
      },
      {
        // 取消收款
        label: '取消收款',
        permission: 'svms:finance:costConfirm.qrcodeCancel',
        show: (record: any) => record.level == 1 && record.feeStatus == 6,
        method: (record: any) => {
          console.log('取消收款', record)

          qrcodeFrom.value = 'costShortOrderQRCodeCancel'
          qcodeTitle.value = '取消收款'
          clickRecord.value = {
            ...record,
            bizType: 1,
            refId: record.orderId,
          }
          payQCodeModal.value = true
        },
      },
    ],
    buttons: [],
    expandable: {},
  })

  // 费用名称全选状态
  const allChangeFeeStatus = ref(false)
  // 费用名称半选状态
  const feeIndeterminate = ref(false)
  // 费用名称全选
  const allChangeFeeName = (val: any) => {
    feeIndeterminate.value = false
    if (val) {
      allChangeFeeStatus.value = true
      queryParam.feeNameIdList = dict.feeNameIdEnum.map((i: any) => {
        return i.value
      })
    } else {
      allChangeFeeStatus.value = false
      queryParam.feeNameIdList = []
    }
  }
  // 选择费用名称
  const changeFeeName = (val: any) => {
    if (val.length === dict.feeNameIdEnum.length) {
      allChangeFeeStatus.value = true
      feeIndeterminate.value = false
    } else if (val.length === 0) {
      allChangeFeeStatus.value = false
      feeIndeterminate.value = false
    } else {
      allChangeFeeStatus.value = false
      feeIndeterminate.value = true
    }
  }
  // 清空费用名称
  const clearFeeName = () => {
    allChangeFeeStatus.value = false
    feeIndeterminate.value = false
  }
  //快捷查询
  const quickSearchClick = (item: any) => {
    queryParam.createTimeRange = []
    queryParam.createTimeBegin = undefined
    queryParam.createTimeEnd = undefined
    queryParam.costType = undefined
    queryParam.feeStatuses = undefined
    queryParam.feeNameIdList = []
    quickSearchData.value.forEach((ele) => {
      if (ele.key == item.key) {
        ele.checked = true
      } else {
        ele.checked = false
      }
    })
    if (item.key == 1) {
      let startTime = dayjs().startOf('month').format('YYYY-MM-DD 00:00:00')
      let endTime = dayjs().endOf('month').format('YYYY-MM-DD 23:59:59')
      queryParam.createTimeRange[0] = startTime
      queryParam.createTimeRange[1] = endTime
      queryParam.createTimeBegin = startTime
      queryParam.createTimeEnd = endTime
    }
    if (item.key == 2) {
      queryParam.costType = 10
      queryParam.feeStatuses = [1, 5]
    }
    if (item.key == 3) {
      queryParam.costType = 20
      queryParam.feeStatuses = [3, 5]
    }
    if (item.key == 4) {
      queryParam.feeStatuses = [1, 5]
      queryParam.feeNameIdList = [12, 13]
    }
    if (item.key == 5) {
      queryParam.feeStatuses = [3, 5]
      queryParam.feeNameIdList = [14, 15]
    }

    loadData()
  }

  // 重置
  const handleReset = () => {
    quickSearchData.value.forEach((ele) => {
      ele.checked = false
    })
    // 清空费用名称
    allChangeFeeStatus.value = false
    feeIndeterminate.value = false
    queryParam.feeNameIdList = []
  }
  // 字段处理
  const tabletolist = (list: any) => {
    list.forEach((el: any) => {
      el.mtype = 'MENU'
      el.level = 1
      if (el.feeDetailList && el.feeDetailList.length) {
        el.children = el.feeDetailList
        el.children.forEach((pl: any) => {
          pl.id = pl.id + 10000 //因折叠根据id问题(父子级id相同)，数据只做展示，故自定义
          pl.mtype = 'TERM1'
          pl.expand = null
          if (pl.type == 0) {
            pl.feeName = pl.feeCategoryName
            pl.totalAmount = pl.amount
          }
          if (pl.type == 1) {
            pl.feeName = pl.itemName
            pl.totalAmount = pl.amount
          }
          if (pl.childrenList && pl.childrenList.length) {
            pl.children = pl.childrenList
            pl.children.forEach((ol: any) => {
              ol.id = ol.id + 60000 //因折叠根据id问题(父子级id相同)，数据只做展示，故自定义
              ol.mtype = 'TERM2'
              ol.expand = null
              ol.feeName = ol.itemName
              ol.totalAmount = ol.amount
              // ol.children = null
            })
          } else {
            return false
          }
        })
      } else {
        return false
      }
    })
    return list
  }

  const feeDetail = ref(null)
  const getListFn = (queryParam: any) => {
    return new Promise((resolve) => {
      getList(queryParam).then((res: any) => {
        feeDetail.value = res.result

        const result = res.result
        const data = tabletolist(result.data) //表
        table.dataList = data
        table.pagination.pageCount = result.total
        resolve({ data, total: result.total })
      })
    })
  }

  const onSearch = () => {
    loadData()
    getNumsApi()
  }

  // 列表接口调用
  const loadData = (pageNumber?: any) => {
    if (isNaN(pageNumber) == false) {
      queryParam.pageNumber = pageNumber
      table.pagination.page = pageNumber
    }
    queryParam.pageNumber = table.pagination.page || 1
    queryParam.pageSize = table.pagination.pageSize
    table.tableLoading = true

    getListFn(queryParam)
      .then((res: any) => {
        console.log('res', res)
      })
      .finally(() => {
        table.tableLoading = false
      })
  }

  const getNumsApi = () => {
    getNums({}).then((res: any) => {
      if (res.code == 200) {
        const result = res.result
        console.log(result)
        quickSearchData.value.forEach((item) => {
          if (item.key == 1) {
            item.value = result.monthAmount || 0
          }
          if (item.key == 2) {
            item.value = result.receivedNotAmount || 0
          }
          if (item.key == 3) {
            item.value = result.payNotAmount || 0
          }
          if (item.key == 4) {
            item.value = result.receivedDepositAmount || 0
          }
          if (item.key == 5) {
            item.value = result.waitBackDepositAmount || 0
          }
        })
      }
    })
  }

  const qcodeConfirm = (details: any) => {
    qcodeCfLoading.value = true

    cancelPay({ id: details.id })
      .then(() => {
        Message.success('取消收款成功')
        payQCodeModal.value = false
      })
      .finally(() => {
        qcodeCfLoading.value = false
      })
  }

  const payQCodeClose = () => {
    table.tableLoading = true
    setTimeout(() => {
      console.log('3s close')
      loadData()
      getNumsApi()
    }, 3000)
  }

  const onALinkClick = (record: any) => {
    navigateTo(`/short-order/detail/${record.orderId}?tab=1&carId=${record.carId}`, `${record.orderCode}-短租详情`)
  }

  const getText = (record: any) => {
    let text = '-'
    if (record) {
      if (record.actualStartTime && record.actualEndTime) {
        text = record.actualStartTime + '-' + record.actualEndTime
      } else if (record.actualStartTime && !record.actualEndTime) {
        text = record.actualStartTime
      } else if (!record.actualStartTime && record.actualEndTime) {
        text = record.actualEndTime
      } else if (!record.actualStartTime && !record.actualEndTime) {
        text = '-'
      }
    }
    return text
  }

  // 确认成功
  const feepageConfirm = () => {
    console.log('确认成功')
    loadData()
    getNumsApi()
  }

  onMounted(() => {
    loadData()
    getNumsApi()
  })
</script>

<style lang="less" scoped>
  .a-link {
    color: rgba(24, 144, 255, 1);
  }
  .box {
    width: 200px;
    height: 40px;
    border: 1px solid wheat;
  }
  .box:hover {
    transform: scale(1.1);
    transition: transform 0.3s;
    position: relative;
    z-index: 999;
  }
  .quick-search {
    display: flex;
    margin-bottom: 20px;
  }
  .quick-search-item {
    width: 16%;
    height: 62px;
    padding: 9px 0 9px 16px;
    border-radius: 4px 4px 4px 4px;
    opacity: 1;
    border: 1px solid #e5e8ef;
  }
  .quick-search-item:hover {
    transform: scale(1.1);
    transition: transform 0.3s;
    position: relative;
    z-index: 999;
  }
  .quick-search-item-checked {
    background: #e8f3ff;
    border-radius: 4px 4px 4px 4px;
    opacity: 1;
    border: 1px solid #1890ff;
  }
  .quick-search-item:nth-of-type(n + 2) {
    margin-left: 20px;
  }
  .quick-search-item-label {
    font-size: 12px;
    font-family: PingFang SC-Regular, PingFang SC;
    font-weight: 400;
    color: #4e5969;
  }
  .quick-search-item-value {
    font-size: 20px;
    font-family: PingFang SC-Semibold, PingFang SC;
    font-weight: 600;
    color: #1d2129;
  }
  .quick-search-item-value-checked {
    color: #1890ff;
  }
  :deep(.arco-table-expand-btn) {
    width: 20px;
    height: 20px;
    background-color: inherit;
  }
  :deep(.arco-table-expand-btn:hover) {
    width: 20px;
    height: 20px;
    background-color: inherit;
  }
  .second-stage {
    width: 200px;
    margin-left: 260px;
  }
  .third-stage {
    width: 200px;
    margin-left: 30px;
  }
</style>
